package com.jyu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jyu.reggie.common.R;
import com.jyu.reggie.entity.User;
import com.jyu.reggie.service.UserService;
import com.jyu.reggie.utils.SMSUtils;
import com.jyu.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();


        if( phone != null){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            System.out.println("============================"+code+"============================");

//            SMSUtils.sendMessage("it鸡腿饭","SMS_267860082","13229014730",code);

//            session.setAttribute(phone, code);

            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);




            return R.success("已发送");
        }

        return R.error("短信发送失败");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        System.out.println(map.toString());

        String phone = (String) map.get("phone");
        String code  = (String) map.get("code");

//        String sessionCode = (String) session.getAttribute(phone);
        Object sessionCode = redisTemplate.opsForValue().get(phone);

        if ( sessionCode != null && sessionCode.equals(code) ){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);

            if( user == null ){
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }

            session.setAttribute("user",user.getId());

            redisTemplate.delete(phone);

            return R.success(user);
        }

        return R.error("登陆失败");
    }
}
